//
//  YSTableTool.m
//  YSSqliteTool_Example
//
//  Created by Kyson on 2018/12/4.
//  Copyright © 2018 kysonyangs. All rights reserved.
//

#import "YSTableTool.h"
#import "YSModelTool.h"
#import "YSSqliteTool.h"

@implementation YSTableTool

+ (NSArray *)tableSortedColumnNames:(Class)cls uid:(NSString *)uid {
    
    NSString *tableName = [YSModelTool tableName:cls];
    
    NSString *createSql = [NSString stringWithFormat:@"select * from sqlite_master where type='table' and name='%@'", tableName];
    
    NSMutableDictionary *dic = [YSSqliteTool querySql:createSql uid:uid].firstObject;
    
    NSString *createTableSql = [dic[@"sql"] lowercaseString];
    if (createSql.length == 0) {
        return nil;
    }
    
    createTableSql = [createTableSql stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    createTableSql = [createTableSql stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    createTableSql = [createTableSql stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    
    NSString *nameTypeStr = [createTableSql componentsSeparatedByString:@"("][1];
    NSArray *nameTypeArr = [nameTypeStr componentsSeparatedByString:@","];
    
    NSMutableArray *names = [NSMutableArray array];
    for (NSString *nameType in nameTypeArr) {
        if ([nameType containsString:@"primary"]) {
            continue;
        }
        
        NSString *nameType2 = [nameType stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];
        
        NSString *name = [nameType2 componentsSeparatedByString:@" "].firstObject;
        [names addObject:name];
    }
    
    names = [names sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
        return [obj1 compare:obj2];
    }].mutableCopy;
    
    return names;
}

+ (BOOL)isTableExists:(Class)cls uid:(NSString *)uid {
    NSString *tableName = [YSModelTool tableName:cls];
    NSString *createSql = [NSString stringWithFormat:@"select * from sqlite_master where type='table' and name='%@'", tableName];
    NSMutableArray *result = [YSSqliteTool querySql:createSql uid:uid];
    return result.count > 0;
}

@end
